const Banners = require("../models/Banners")

const addBanner = async (req, res) => {
    try {
        const foundbynum= await Banners.findOne({ num: req.body.num})
        const Bannersfound = await Banners.findOne({ id_drama: req.body.id_drama});
        if (Bannersfound&&(req.body.num!=Bannersfound.num)) {
            return res.status(200).json({ error_msg: "剧本重复" });
        }
        else{
            if(foundbynum){
                foundbynum.id_drama=req.body.id_drama
                const Bannersave = await foundbynum.save()
                return res.status(200).json({ success: Bannersave });
            }
            else if(!foundbynum) {
                const Bannersave = await Banners(req.body).save()
                return res.status(200).json({ success: Bannersave });
            }
        }
 
        

    } catch (err) {
        return res.status(400).json({ error_msg: err.message });
    }
}


const getBanner = async (req, res) => {
    try {
        const foundquery = req.query
        for (item in foundquery) {
            foundquery[item] = eval("/" + foundquery[item] + "/")
        }
        const storefound = await Banners.find(foundquery).sort("num").populate("id_drama")
        if (!storefound) {
            return res.status(200).json({ error_msg: "未找到" });
        }
        return res.status(200).json({ success: storefound });
    }
    catch (err) {
        return res.status(400).json({ error_msg: err.message });
    }
}
module.exports = { addBanner, getBanner }